package org.anti996.bankms.controller;

import org.anti996.bankms.dao.AdminDao;
import org.anti996.bankms.dao.UserDao;
import org.anti996.bankms.model.Account;
import org.anti996.bankms.model.Card;
import org.anti996.bankms.util.IOUtil;
import org.anti996.bankms.util.MessageUtil;
import org.anti996.bankms.view.AdminView;

import java.util.ArrayList;
import java.util.List;

public class AdminController extends ControllerBase {
    private boolean adminLogin_ = false;
    private List<Account> accounts_ = null;
    private int retryTimes_ = 4;

    public AdminController() {
        super(new AdminView());
    }

    private void login() {
        MessageUtil.info("请输入用户名：");
        String username = IOUtil.parseInput();
        MessageUtil.info("请输入密码：");
        String password = IOUtil.parsePassword();
        if (username.equals("admin") && password.equals("666666")) {
            adminLogin_ = true;
            accounts_ = AdminDao.getAllAccounts();
            MessageUtil.success("登录成功");
        }
    }

    @Override
    public void deal() {
        if (!adminLogin_) {
            if (0 < retryTimes_ && retryTimes_ < 4) {
                MessageUtil.warning("用户名或密码错误，请重新输入，还可尝试" + retryTimes_ + "次");
            } else if (retryTimes_ == 0) {
                MessageUtil.error("用户名或密码错误，登录失败");
                Navigator.pop();
                return;
            } else if (retryTimes_ == 4) {
                MessageUtil.title("管理员登录");
            }
            login();
            --retryTimes_;
        } else {
            super.deal();
            int order = IOUtil.parseOrder();
            switch (order) {
                case 1 -> {
                    refresh();
                    MessageUtil.title("查询用户信息");
                    MessageUtil.itemList(new String[]{"通过用户名查找", "显示全部用户"});
                    MessageUtil.info("请输入您的选择：");
                    switch (IOUtil.parseOrder()) {
                        case 1 -> {
                            MessageUtil.info("请输入用户名：");
                            String username = IOUtil.parseInput();
                            Account account = AdminDao.selectByUsername(username);
                            if (account == null) {
                                MessageUtil.error("查询失败，不存在该用户");
                            } else {
                                MessageUtil.success("查询成功");
                                MessageUtil.infoln(Account.describe(account));
                            }
                        }
                        case 2 -> {
                            String[] accountList = new String[accounts_.size()];
                            for (int i = 0; i < accounts_.size(); i++) {
                                Account a = accounts_.get(i);
                                accountList[i] = Account.describe(a);
                            }
                            MessageUtil.itemList(accountList);
                        }
                    }
                    waitForKeyPress();
                }
                case 2 -> {
                    refresh();
                    MessageUtil.title("修改用户信息");
                    MessageUtil.info("请输入用户名：");
                    String username = IOUtil.parseInput();
                    if (!username.isBlank()) {
                        Account account = AdminDao.selectByUsername(username);
                        if (account == null) {
                            MessageUtil.error("不存在该用户");
                            waitForKeyPress();
                        } else {
                            MessageUtil.infoln("已选中用户：");
                            MessageUtil.infoln(Account.describe(account));
                            waitForKeyPress();
                            Navigator.push(new UserInfoUpdateController(account));
                        }
                    }
                }
                case 3 -> {
                    // 增加用户
                    refresh();
                    MessageUtil.title("增加用户界面");
                    MessageUtil.infoln("请输入要增加的用户信息：");
                    MessageUtil.info("用户名：");
                    String username = IOUtil.parseInput();
                    MessageUtil.info("密码：");
                    String password = IOUtil.parsePassword();
                    MessageUtil.info("姓名：");
                    String name = IOUtil.parseInput();
                    MessageUtil.info("身份证号：");
                    String idnumber = IOUtil.parseInput();
                    MessageUtil.info("籍贯：");
                    String hometown = IOUtil.parseInput();
                    MessageUtil.info("预留手机号：");
                    String phone = IOUtil.parseInput();
                    Account a = new Account();
                    a.setUsername(username);
                    a.setPasswd(password);
                    a.setName(name);
                    a.setIdnumber(idnumber);
                    a.setHometown(hometown);
                    a.setPhone(phone);
                    boolean flag = AdminDao.add(a);
                    if (flag) {
                        MessageUtil.success("开户成功");
                        accounts_ = AdminDao.getAllAccounts();
                    } else
                        MessageUtil.warning("开户失败");
                    waitForKeyPress();
                }
                case 4 -> {
                    //删除用户
                    refresh();
                    MessageUtil.title("删除用户界面");
                    MessageUtil.infoln("请输入要删除的用户名：");
                    String username = IOUtil.parseInput();
                    boolean flag = AdminDao.delete(username);
                    if (flag) {
                        MessageUtil.success("销户成功");
                        accounts_ = AdminDao.getAllAccounts();
                    } else
                        MessageUtil.warning("销户失败");
                    waitForKeyPress();
                }
                case 5 -> {
                    refresh();
                    MessageUtil.title("查询银行卡信息");
                    MessageUtil.itemList(new String[]{"通过卡号查找", "显示全部银行卡"});
                    MessageUtil.info("请输入您的选择：");
                    switch (IOUtil.parseOrder()) {
                        case 1 -> {
                            MessageUtil.info("请输入卡号：");
                            String input = IOUtil.parseInput();
                            if (input.isBlank()) break;
                            int id = Integer.parseInt(input);
                            Card card = UserDao.getCardById(id);
                            if (card == null) {
                                MessageUtil.error("查询失败，不存在该银行卡");
                            } else {
                                MessageUtil.success("查询成功");
                                MessageUtil.infoln("该卡属于用户" + card.getUsername());
                                MessageUtil.infoln(Card.describe(card));
                            }
                        }
                        case 2 -> {
                            List<Card> cards = UserDao.getAllCardsSortByUsername();
                            if (cards.size() == 0) {
                                MessageUtil.warning("当前并无银行卡");
                            } else {
                                List<String> tmpList = new ArrayList<>();
                                int i = 0;
                                String curname = cards.get(0).getUsername();
                                do {
                                    String s = cards.get(i).getUsername();
                                    if (!curname.equals(s)) {
                                        MessageUtil.infoln(String.format("用户%s有%d张银行卡：", curname, tmpList.size()));
                                        MessageUtil.itemList(tmpList.toArray(new String[0]));
                                        tmpList.clear();
                                        curname = s;
                                    }
                                    tmpList.add(Card.describe(cards.get(i)));
                                    ++i;
                                } while (i < cards.size());
                                MessageUtil.infoln(String.format("用户%s有%d张银行卡：", curname, tmpList.size()));
                                MessageUtil.itemList(tmpList.toArray(new String[0]));
                            }
                        }
                    }
                    waitForKeyPress();
                }
                case 6 -> {
                    refresh();
                    MessageUtil.title("修改银行卡余额");
                    MessageUtil.info("请输入卡号：");
                    String input = IOUtil.parseInput();
                    if (!input.isBlank()) {
                        int card_id = Integer.parseInt(input);
                        Card card = UserDao.getCardById(card_id);
                        if (card == null) {
                            MessageUtil.error(String.format("系统并不存在卡号为%d的卡", card_id));
                        } else {
                            MessageUtil.infoln("已选中卡：");
                            MessageUtil.infoln(Card.describe(card));
                            MessageUtil.info("输入余额：");
                            double bl = Double.parseDouble(IOUtil.parseInput());
                            boolean result = UserDao.updateBalance(card, bl);
                            if (result) {
                                MessageUtil.success("修改成功");
                            } else {
                                MessageUtil.error("修改失败");
                            }
                        }
                    }
                    waitForKeyPress();
                }
                case 7 -> {
                    refresh();
                    MessageUtil.title("办卡界面");
                    MessageUtil.infoln("请输入办卡信息：");
                    MessageUtil.info("用户名：");
                    String username = IOUtil.parseInput();
                    MessageUtil.info("币种：");
                    String currency = IOUtil.parseInput();
                    Card card = new Card();
                    card.setUsername(username);
                    card.setCurrency(currency);
                    boolean flag = AdminDao.AddNewCard(card);
                    if (flag)
                        MessageUtil.success("办卡成功");
                    else
                        MessageUtil.warning("办卡失败");
                    waitForKeyPress();
                }
                case 8 -> {
                    refresh();
                    MessageUtil.title("销卡界面");
                    MessageUtil.infoln("请输入销卡信息：");
                    MessageUtil.info("银行卡号：");
                    int id = Integer.parseInt(IOUtil.parseInput());
                    boolean flag = AdminDao.DeleteCard(id);
                    if (flag)
                        MessageUtil.success("销卡成功");
                    else
                        MessageUtil.warning("销卡失败");
                    waitForKeyPress();
                }
                case 9 -> {
                    refresh();
                    MessageUtil.title("修改汇率");
                    List<String> lines = new ArrayList<>();
                    for (var cur : UserDao.CURRENCY_NAMES.keySet()) {
                        lines.add(String.format("币种：%s，名称：%s，汇率：%s", cur, UserDao.CURRENCY_NAMES.get(cur), UserDao.CURRENCY_RATES.get(cur)));
                    }
                    MessageUtil.itemList(lines.toArray(new String[0]));
                    MessageUtil.info("请输入币种：");
                    String cur = IOUtil.parseInput();
                    if (!cur.isBlank()) {
                        boolean newBi = !UserDao.CURRENCY_NAMES.containsKey(cur);
                        String name = null;
                        if (newBi) {
                            MessageUtil.info("请输入名称：");
                            name = IOUtil.parseInput();
                        }
                        MessageUtil.info("请输入汇率：");
                        double rate = Double.parseDouble(IOUtil.parseInput());
                        boolean flag = newBi ? AdminDao.addCurrency(cur, name, rate)
                                : AdminDao.updateCurrency(cur, rate);
                        if (flag)
                            MessageUtil.success("修改成功");
                        else
                            MessageUtil.warning("修改失败");
                    }
                    waitForKeyPress();
                }
                case 10 -> Navigator.pop();
                default -> wrongInputAndRetry();
            }
        }
    }
}




